package com.imooc.luckymoney.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class HttpAspect {
    public static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * 定义一个切点
     * 1）execution(* *(..))
     * //表示匹配所有方法
     * 2）execution(public * com. savage.service.UserService.*(..))
     * //表示匹配com.savage.server.UserService中所有的公有方法
     * 3）execution(* com.savage.server..*.*(..))
     * //表示匹配com.savage.server包及其子包下的所有方法
     */
    @Pointcut("execution(public * com.imooc.luckymoney.controller.CrudController.*(..))")
    public void log(){
    }

    /**
     * 在方法调用前记录执行，记录相关的日志信息
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
//        Gson gson = new Gson();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        logger.info("url={}", request.getRequestURL());

        //method
        logger.info("method={}", request.getMethod());

        //ip
        logger.info("ip={}", request.getRemoteAddr());

        //类方法
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //参数
        logger.info("args={}", joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter() {
        logger.info("222222222222");
    }

    /**
     * 记录方法的返回值
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        logger.info("response={}", object != null? object.toString() : null);
    }
}
